<?php
namespace app\appclass\controller;
use app\AdminRest;

use app\appclass\model\CardList;
use app\appclass\model\CardLog;
use app\appclass\model\CardUser;
use app\appclass\model\CardWater;
use app\appclass\model\ClassCate;
use app\appclass\model\ClassLable;
use app\appclass\model\ClassList;
use app\appclass\model\ClassRoom;
use app\card\model\UserPhone;
use app\shop\model\IndexUser;
use longbingcore\wxcore\Excel;
use think\App;
use think\facade\Db;


class AdminCardUser extends AdminRest
{

    protected $model;

    protected $cate_model;

    protected $lable_model;

    protected $room_model;

    public function __construct(App $app) {

        parent::__construct($app);

        $this->model       = new CardUser();

        $this->cate_model  = new ClassCate();

        $this->lable_model = new ClassLable();

        $this->room_model  = new ClassRoom();

    }


    /**
     * @author chenniang
     * @DataTime: 2021-05-11 17:50
     * @功能说明:会员列表
     */

    public function cardUserList(){

        $input = $this->_param;
        //初始化会员卡
        $this->model->initCard($this->_uniacid);

        $this->model->initCardUserAll($this->_uniacid);

        $dis[] = ['a.uniacid' ,'=', $this->_uniacid];

        if(!empty($input['status'])){

            $dis[] = ['a.status','=',$input['status']];

        }else{

            $dis[] = ['a.status','>',-1];
        }

        if(!empty($input['store_id'])){

            $dis[] =['a.store_id','=',$input['store_id']] ;
        }

        $where = [];

        //昵称
        if(!empty($input['name'])){

            $where[] = ['b.nickName','like','%'.$input['name'].'%'];

            $where[] = ['a.user_name','like','%'.$input['name'].'%'];

            $where[] = ['a.mobile','like','%'.$input['name'].'%'];

        }
        //卡名称
        if(!empty($input['card_name'])){

            $dis[] = ['c.title','like','%'.$input['card_name'].'%'];
        }
        //卡类型
        if(isset($input['card_type'])){

            $dis[] = ['a.card_type','=',$input['card_type']];
        }
        //有效期
        if(!empty($input['e_end_time'])){

            $start_time = $input['e_start_time'];

            $end_time   = $input['e_end_time'];

            $dis[] = ['a.end_time','between',"$start_time,$end_time"];
        }
        //开卡时间
        if(!empty($input['c_end_time'])){

            $start_time = $input['c_start_time'];

            $end_time   = $input['c_end_time'];

            $dis[] = ['a.create_time','between',"$start_time,$end_time"];
        }
        //是否认证
        if(isset($input['is_auth'])){

            if($input['is_auth']==1){

                $dis[] = ['a.user_id','<>',0];

            }else{

                $dis[] = ['a.user_id','=',0];

            }

        }

        $data = $this->model->dataList($dis,$input['limit'],$where);

        return $this->success($data);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-05-12 11:19
     * @功能说明:绑定会员
     */
    public function cardUserAdd(){

        $input = $this->_input;

        $input['uniacid'] = $this->_uniacid;

        $res = $this->model->bindUser($input);

        return $this->success($res);

    }



    /**
     * @author chenniang
     * @DataTime: 2021-06-02 10:26
     * @功能说明:excel倒入会员卡信息
     */
    public function importUserCard(){

        $input = $this->_input;

        $data  = $input['data'];

        $card_model = new CardList();

        $phone_model= new UserPhone();

        $user_model = new IndexUser();

        foreach ($data as $v){

            $card = $card_model->dataInfo(['id'=>$v['card_id'],'uniacid'=>$this->_uniacid]);

            if(empty($card)||$card['status']==-1){

                $this->errorMsg('会员卡未找到,id:'.$v['card_id']);
            }

            if(empty($v['mobile'])){

                $this->errorMsg('电话号码不能为空');
            }

            $user_id = $phone_model->where(['uniacid'=>$this->_uniacid,'phone'=>$v['mobile']])->value('user_id');

            $user_id = !empty($user_id)?$user_id:0;

            $adviser = $user_model->where(['id'=>$v['adviser']])->find();

            if(empty($adviser)){

                $this->errorMsg('销售顾问未找到,id:'.$v['adviser']);
            }

            $insert = [

                'uniacid'   => $this->_uniacid,

                'user_id'   => $user_id,

                'code'      => longbingorderCode(),

                'pay_type'  => $v['pay_type'],

                'card_type' => $card['type'],

                'pay_price' => $v['pay_price'],

                'card_id'   => $card['id'],

                'value'     => $card['value'],

                'discount'  => !empty($v['discount'])?$v['discount']:0,

                'true_value'=> $v['true_value'],

                'open_time' => strtotime(excelTime($v['open_time'])),

                'adviser'   => $v['adviser'],

                'text'      => !empty($v['text'])?$v['text']:'',

                'store_id'  => $card['store_id'],

                'mobile'    => $v['mobile'],

                'end_time'  => strtotime(excelTime($v['end_time'])),

                'status'    => $v['status'],

                'import'    => 1,

                'user_name' => $v['nickName'],

                'create_time' => strtotime(excelTime($v['create_time'])),

                'is_cancel' => in_array($v['status'],[-1,5])?1:0

            ];

            $res = $this->model->insert($insert);

        }

        return $this->success($res);

    }



    /**
     * @author chenniang
     * @DataTime: 2020-02-17 16:08
     * @功能说明:获取下载地址
     */
    public function getExcelPath(){
        //实例化excel的类
        $excel = new Excel();
        //名字
        $name  ='导入会员卡信息';
        //标题
        $header=[
            '会员昵称',
            '手机号',
            '会员卡ID',
            '会员卡名称',
            '支付方式',
            '支付价格',
            '优惠',
            '余额',
            '开卡时间',
            '发卡时间',
            '顾问ID',
            '备注',
            '有效期',
            '状态',

        ];
        //导出
        $fileName=$excel->excelExport($name,$header,[]);

        return $this->success($fileName);

    }

    /**
     * @author chenniang
     * @DataTime: 2021-05-18 10:50
     * @功能说明:查询用户
     */
    public function userList(){

        $input = $this->_param;

        if(empty($input['name'])){

            return $this->success([]);
        }

        $dis[] = ['a.uniacid','=',$this->_uniacid];

        $dis[] = ['a.nickName','like','%'.$input['name'].'%'];

        $user_model = new IndexUser();

        $data = $user_model->alias('a')
                ->join('longbing_card_user_phone b','a.id = b.user_id','left')
                ->where($dis)
                ->field('a.id,a.nickName,b.phone')
                ->group('a.id')
                ->select()
                ->toArray();


        return $this->success($data);
    }


    /**
     * @author chenniang
     * @DataTime: 2021-06-03 15:06
     * @功能说明:编辑会员卡
     */
    public function cardUserUpdate(){

        $input = $this->_input;

        $dis = [

            'id' => $input['id']
        ];

        $data = $this->model->dataInfo($dis);

        Db::startTrans();

        if(in_array($data['status'],[1,2,3])){

            $input['status'] = 2;

            if($input['open_time']>time()){

                $input['status'] = 1;
            }

//            if($input['end_time']<time()){
//
//                $input['status'] = 3;
//            }

            if($data['status']==1&&$input['status']==2){

                $res = $this->model->controlCard($input['id'],2,$this->_uniacid);

                if($res!=true){

                    Db::rollback();

                    $this->errorMsg('编辑失败');
                }

            }

        }

        $res = $this->model->dataUpdate($dis,$input);
//        //添加流水记录
//        $water_model = new CardWater();
//
//        $res = $water_model->controlWater($data,$input['true_value'],$input['text']);
//
//        if($res==0){
//
//            Db::rollback();
//
//            $this->errorMsg('编辑失败');
//        }

        Db::commit();

        return $this->success($res);

    }

    /**
     * @author chenniang
     * @DataTime: 2021-05-20 11:17
     * @功能说明:会员卡详情
     */
    public function cardUserInfo(){

        $input = $this->_param;

        $dis = [

            'id' => $input['id']
        ];

        $data = $this->model->dataInfo($dis);

        $data['adviser_name'] = lbUserName($data['adviser']);

        $data['end_time']     = date('Y-m-d H:i:s',$data['end_time']);

        $data['create_time']  = date('Y-m-d H:i:s',$data['create_time']);

        $data['open_time']    = date('Y-m-d H:i:s',$data['open_time']);

        $data['user_name']    = !empty($data['user_id'])?lbUserName($data['user_id']):$data['user_name'];

        $data['user_avatar']  = lbUserAvatar($data['user_id']);

        return $this->success($data);
    }



    /**
     * @author chenniang
     * @DataTime: 2021-06-09 14:28
     * @功能说明:会员卡变更记录
     */
    public function cardLogList(){

        $input = $this->_param;

        $dis = [

            'card_user_id' => $input['card_id']
        ];

        $log_model = new CardLog();

        $data = $log_model->dataList($dis,$input['limit']);

        return $this->success($data);
    }


    /**
     * @author chenniang
     * @DataTime: 2021-06-09 14:30
     * @功能说明:会员卡记录
     */
    public function waterList(){

        $input = $this->_param;

        $water_model = new CardWater();

        $dis = [

            'card_id' => $input['card_id']

        ];

        $data = $water_model->waterList($dis,$input['limit']);

        return $this->success($data);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-06-03 14:18
     * @功能说明:停卡
     */
    public function stopCard(){

        $input = $this->_input;

        $dis = [

            'id' => $input['id']
        ];

        $data = $this->model->dataInfo($dis);

        if($data['status']==4){

            $this->errorMsg('已停卡');
        }

        if($data['status']==5){

            $this->errorMsg('已退卡,无法停卡');

        }

        $res = $this->model->controlCard($input['id'],4,$this->_uniacid);

        return $this->success($res);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-06-03 14:18
     * @功能说明:退卡
     */
    public function returnCard(){

        $input = $this->_input;

        $dis = [

            'id' => $input['id']
        ];

        $data = $this->model->dataInfo($dis);

        if($data['status']==5){

            $this->errorMsg('已退卡,无法停卡');

        }

       // $res = $this->model->controlCard($input['id'],5,$this->_uniacid);

        $res = $this->model->controlCard($input['id'],5,$this->_uniacid,0,1,$input['cancel_price'],$input['cancel_type']);


        return $this->success($res);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-06-09 11:44
     * @功能说明:开卡
     */
    public function openCard(){

        $input = $this->_input;

        $dis = [

            'id' => $input['id']
        ];

        $data = $this->model->dataInfo($dis);

        if($data['status']!=4){

            $this->errorMsg('只有处于停卡状态的卡，才能开卡');

        }

        $log_model = new CardLog();
        //查询上一次停卡的信息
        $stop_info = $log_model->where(['card_user_id'=>$input['id'],'status'=>4])->order('create_time desc')->find();

        if(empty($stop_info)){

            $this->errorMsg('未找到上次停卡信息');

        }

        $stop_info = $stop_info->toArray();
        //过期时间
        $end_time = time()-$stop_info['create_time']+$data['end_time'];

        $status = 2;
        //判断状态
        if($data['open_time']>time()){

            $status = 1;
        }

        $update = [

            'end_time' => $end_time,

            'status'   => $status
        ];

        Db::startTrans();
        //修改会员卡信息
        $res = $this->model->dataUpdate($dis,$update);

        if($res==0){

            Db::rollback();

            $this->errorMsg('开卡失败');
        }
        //添加操作日志
        $res = $this->model->controlCard($input['id'],2,$this->_uniacid);

        if($res==0){

            Db::rollback();

            $this->errorMsg('开卡失败');
        }

        Db::commit();

        return $this->success($res);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-06-03 15:02
     * @功能说明:删除卡
     */
    public function delCard(){

        $input = $this->_input;

        $res = $this->model->controlCard($input['id'],-1,$this->_uniacid);

        return $this->success($res);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-06-30 17:33
     * @功能说明:续卡
     */
    public function renewCard(){

        $input = $this->_input;

        $log_model = new CardLog();

        $water_model= new CardWater();

        $card_model = new CardList();

        $card = $this->model->dataInfo(['id'=>$input['id']]);

        $top_card = $card_model->dataInfo(['id'=>$card['card_id']]);

        if(empty($top_card)||$top_card['status']==-1){

            $this->errorMsg('该会员卡已被删除');
        }

        Db::startTrans();

        $insert = [

            'uniacid'      => $this->_uniacid,

            'card_user_id' => $input['id'],

            'status'       => 7,

            'create_time'  => time(),

            'price'        => $input['price'],

            'value'        => !empty($input['value'])?$input['value']:0,

            'before_value' => $card['true_value'],

            'after_value'  => !empty($input['value'])?$input['value']+$card['true_value']:$card['true_value'],

            'before_end_time' => $card['end_time'],

            'after_end_time'  => $input['end_time'],

            'text'          => $input['text'],

        ];

        $res = $log_model->insert($insert);

        if($res==0){

            Db::rollback();

            $this->errorMsg('续开失败');

        }

        $update = [

            'pay_price' => round($card['pay_price']+$input['price'],2),

            'true_value'=> $insert['after_value'],

            'end_time'  => $insert['after_end_time']

        ];

        $res = $this->model->dataUpdate(['id'=>$input['id']],$update);

        if($res==0){

            Db::rollback();

            $this->errorMsg('续开失败');

        }
        //期限卡没有
        if($card['card_type']!=0){
            //变更余额明细
            $res = $water_model->renewCardWater($card,$input['value']);

            if($res==0){

                Db::rollback();

                $this->errorMsg('续开失败');

            }

        }

        Db::commit();

        return $this->success($res);

    }



}
